#include <iostream>
#include <memory>
#include <string>
#include <fstream>
#include <unistd.h>

#include "TcpServer.hpp"
#include "HttpProtocol.hpp"
#include "Session.hpp"

using namespace std;
using namespace Net_Work;

string SuffixToType(const string &suffix)
{
    if (suffix == ".html" || suffix == ".html")
        return "text/html";
    else if (suffix == ".png")
        return "image/png";
    else if (suffix == ".jpg")
        return "image/jpg";
    else
        return "text/html";
}
string CodetoDesc(int code)
{
    switch (code)
    {
    case 200:
        return "OK";
    case 301:
        return "Moved Permanently";
    case 307:
        return "Temporary Redirect";
    case 403:
        return "Forbidden";
    case 404:
        return "Not Found";
    case 500:
        return "Internal Server Error";
    default:
        return "Unknown";
    }
}

SessionManager onlineuser;

// 网络负责IO发送
// HandlerRequest字节流数据解析和调用业务处理方法的
// 处理报文的方法
// request: 我们认为我们已经读到了一个完整的请求了
std::string HandlerHttpRequest(std::string &request)
{
    HttpRequest req;
    // 反序列化
    req.Deserialize(request);
    req.Parse();
    req.DebugHttp();
    int code = 200;

    std::string content = req.GetFileContent();
    if (content.empty())
    {
        code = 404;
        content = req.Get_404();
    }
    HttpResponse resp;
    if (req.Url() == "/resigster")
    {
        // username passwd
        std::string sessionid = onlineuser.AddSession("user", "passwd");
        std::string session = "Set-cookie : sessionid=" + sessionid;
        resp.AddHeader(session);
    }
    if (req.Url() == "/login")
    {
        // username;passwd
        std::string sessionid;
        if (onlineuser.SearchSession(sessionid))
            ;
        resp.AddHeader(sessionid);
    }

    // code = 301;

    resp.SetCode(code);
    resp.SetDesc(CodetoDesc(code));
    resp.MakeStatusLine();
    std::string content_len_str = "Content-Length: " + std::to_string(content.size()) + "\r\n";
    resp.AddHeader(content_len_str);
    std::string content_type_str = "Content-Type: " + SuffixToType(req.Suffix()) + "\r\n";
    resp.AddHeader(content_type_str);

    std::string namecookie = "Set-Cookie: username=zhangsan\r\n";
    resp.AddHeader(namecookie);
    std::string passwdcookie = "Set-Cookie: passwd=123456\r\n";
    resp.AddHeader(passwdcookie);
    std::string statuscookie = "Set-Cookie: status=logined\r\n";
    resp.AddHeader(statuscookie);

    resp.AddContent(content);

    return resp.Serialize();
}

// ./server port
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        std::cout << "Usage : " << argv[0] << " port" << std::endl;
        return 0;
    }
    uint16_t localport = std::stoi(argv[1]);

    std::unique_ptr<TcpServer> svr(new TcpServer(localport, HandlerHttpRequest));

    svr->Loop();

    return 0;
}